import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const history = createWebHistory()
const routes=[{
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
}]
const list: Array<RouteRecordRaw> = [{
    path: '/',
    name: 'index',
    redirect: '/home',
    component: () => import('@/components/layout.vue'),
    children: [
        {
            path: '/home',
            name: 'home',
            component: () => import('../views/home/index.vue')
        }, 
        {
            path: '/news',
            name: 'news',
            component: () => import('../views/news/index.vue')
        }, 
        {
            path: '/grammar',
            name: 'grammar',
            component: () => import('@/views/grammar/index.vue'),
        },
        {
            path: '/css',
            name: 'css',
            component: () => import('@/views/css/index.vue'),
        },
        {
            path: '/mine',
            name: 'mine',
            redirect:'/mine/info',
            component: () => import('../views/mine/index.vue'),
            children: [
                {
                    path: 'info',
                    name: 'mineinfo',
                    component: () => import('../views/mine/info/index.vue'),
                },
                {
                    path: 'task',
                    name: 'mytask',
                    component: () => import('../views/mine/task/index.vue'),
                }
            ]
        }
    ]
},


]
const router = createRouter({
    history,
    routes
})
// const router = createRouter([]);

router.beforeEach((to,from,next)=>{
	// 已经添加动态路由
	if(router.options.hasDynamicRoutes){
		let token=sessionStorage.getItem("token")||''
		// 这里可以添加登录判断等逻辑
		if(token){
			console.log(2)
			if(to.path.includes('login')){
				console.log(4)
				next({path:'/'})
			}else{
				console.log(5)
				next()
			}
			
			
		} else {
			console.log(3)
			if(to.path.includes('login')){
				next()
			}else{
				next({path:'/login'})
			}
			
		}
		
	} else {
		// 获取动态路由
		getRoutes()
		next({ ...to, replace: true });
	}
})
// 通过接口等方式获取路由
function getRoutes(){
	console.log(1)
	dynamicRoutesBuilder(list)
}
// 处理和注册路由
function dynamicRoutesBuilder(menuList=[],routes=[]){
	console.log('router',router)
	const dynamicRoutes=menuList
	dynamicRoutes.forEach(item=>{
		router.addRoute(item);
	})
	router.addRoute({ path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('@/views/404/index.vue') })
	// router.addRoute({ path: "*", name: "404", component: () => import('@/views/404/index.vue') })
	
	router.options.hasDynamicRoutes = true;
}

export default router